const http = require("http");
const express = require("express");
const app = express();
const server = http.createServer(app);
const path = require("path");
const fs = require("fs");
const io = require("socket.io")(server);

var bodyParser = require("body-parser");
// 使用中间件
app.use(bodyParser.json()); // 支持 json 格式
// 使用第三方插件 qs 来处理
app.use(bodyParser.urlencoded({ extended: true }));

app.use(express.static(path.join(__dirname, "./public")));
createWatcher();

function createWatcher() {
  const absolute = "./public";
  fs.watch(absolute, function (eventType, filename) {
    if (filename) {
      io.sockets.emit("reload");
    }
  });
}

function test(){
  let href=window.location.href;
  href = href.split('?')[0] + '?'+ new Date().getTime();

  console.log(href);
  io.connect(href).on('reload',()=>window.location.reload());
}

app.post("/changeContent", (req, res) => {
  // console.log(req.body);
  let str = req.body["content"];
  let start =
    '<html lang="zh-CN"><head><meta charset="UTF-8"/><title>热更新页面</title></head><body><article style="font-size: 30px;">';
  let end =
    '</article><script src="./socket.io.min.js"></script><script type="module">let href=window.location.href;href = href.split(\'?\')[0] + \'?\'+ new Date().getTime();console.log(href);io.connect(href).on(\'reload\',()=>window.location.href=href);</script></body></html>';
  let data = start + str + end;
  let message = "Successfully";
  fs.writeFile("./public/index.html", data, (err) => {
    if (err) {
      console.log(err);
      message = err;
    }
  });
  res.send(message);
});

server.listen(8086, function () {
  console.log(`The server is running on port 8086.`);
});
